import 'package:get/get.dart';
import 'package:raze/lore/glyph/whisper_essence.dart';

/// 单聊状态管理
/// 全局单聊消息状态，提供消息发送、已读标记、对话查询等功能
class WhisperChronicle extends GetxController {
  // 所有消息列表
  final _messageList = <WhisperEssence>[].obs;

  /// 获取所有消息列表
  List<WhisperEssence> get messageList => _messageList;

  @override
  void onInit() {
    super.onInit();
    _initializeDefaultMessages();
  }

  /// 初始化默认消息数据
  void _initializeDefaultMessages() {
    final now = DateTime.now();

    // 围绕 admin (id: '1') 创建默认聊天数据
    // admin 与用户2的对话
    _messageList.value = [
      WhisperEssence(
        id: '1',
        senderId: '1',
        receiverId: '2',
        messageType: 'text',
        content: 'Hey, how are your plants doing after the rain?',
        isRead: true,
        createTime: now.subtract(const Duration(days: 2, hours: 5)),
      ),
      WhisperEssence(
        id: '2',
        senderId: '2',
        receiverId: '1',
        messageType: 'text',
        content: 'They look amazing! The leaves are so vibrant now.',
        isRead: true,
        createTime: now.subtract(
          const Duration(days: 2, hours: 4, minutes: 30),
        ),
      ),
      WhisperEssence(
        id: '3',
        senderId: '1',
        receiverId: '2',
        messageType: 'text',
        content: 'That\'s great! Would you like to share some photos?',
        isRead: true,
        createTime: now.subtract(const Duration(days: 2, hours: 4)),
      ),
      WhisperEssence(
        id: '4',
        senderId: '2',
        receiverId: '1',
        messageType: 'call_failed',
        content: '',
        isRead: false,
        createTime: now.subtract(const Duration(days: 1, hours: 10)),
      ),

      // admin 与用户3的对话
      WhisperEssence(
        id: '5',
        senderId: '3',
        receiverId: '1',
        messageType: 'text',
        content: 'Hi! I saw your post about plant care. Can you help me?',
        isRead: true,
        createTime: now.subtract(const Duration(days: 1, hours: 8)),
      ),
      WhisperEssence(
        id: '6',
        senderId: '1',
        receiverId: '3',
        messageType: 'text',
        content: 'Of course! What do you need help with?',
        isRead: true,
        createTime: now.subtract(
          const Duration(days: 1, hours: 7, minutes: 45),
        ),
      ),
      WhisperEssence(
        id: '7',
        senderId: '3',
        receiverId: '1',
        messageType: 'text',
        content: 'My plant leaves are turning yellow after watering.',
        isRead: false,
        createTime: now.subtract(const Duration(hours: 12)),
      ),

      // admin 与用户4的对话
      WhisperEssence(
        id: '8',
        senderId: '1',
        receiverId: '4',
        messageType: 'text',
        content: 'Hello! Thanks for the answer on my question.',
        isRead: true,
        createTime: now.subtract(const Duration(hours: 6)),
      ),
      WhisperEssence(
        id: '9',
        senderId: '4',
        receiverId: '1',
        messageType: 'text',
        content: 'You\'re welcome! Happy to help.',
        isRead: true,
        createTime: now.subtract(const Duration(hours: 5, minutes: 30)),
      ),
      WhisperEssence(
        id: '10',
        senderId: '1',
        receiverId: '4',
        messageType: 'call_failed',
        content: '',
        isRead: false,
        createTime: now.subtract(const Duration(hours: 3)),
      ),

      // admin 与用户5的对话
      WhisperEssence(
        id: '11',
        senderId: '5',
        receiverId: '1',
        messageType: 'text',
        content: 'Good morning! How was your garden after the heavy rain?',
        isRead: false,
        createTime: now.subtract(const Duration(hours: 2)),
      ),
    ];
  }

  /// 发送消息
  /// [senderId] 发送者用户ID
  /// [receiverId] 接收者用户ID
  /// [messageType] 消息类型：'text' 或 'call_failed'
  /// [content] 消息内容
  /// 返回创建的消息ID
  String dispatchMessage({
    required String senderId,
    required String receiverId,
    required String messageType,
    required String content,
  }) {
    final newId = (_messageList.length + 1).toString();
    final newMessage = WhisperEssence(
      id: newId,
      senderId: senderId,
      receiverId: receiverId,
      messageType: messageType,
      content: content,
      isRead: false,
      createTime: DateTime.now(),
    );
    _messageList.add(newMessage);
    return newId;
  }

  /// 标记消息为已读
  /// [messageId] 消息ID
  /// 返回操作结果，成功返回true，失败返回false（消息不存在）
  bool markMessageAsRead(String messageId) {
    final index = _messageList.indexWhere((msg) => msg.id == messageId);
    if (index == -1) {
      return false; // 消息不存在
    }

    final message = _messageList[index];
    if (message.isRead) {
      return true; // 已经已读
    }

    _messageList[index] = message.copyWith(isRead: true);
    return true;
  }

  /// 标记与某个用户的所有未读消息为已读
  /// [currentUserId] 当前用户ID
  /// [otherUserId] 对方用户ID
  void markConversationAsRead(String currentUserId, String otherUserId) {
    for (int i = 0; i < _messageList.length; i++) {
      final message = _messageList[i];
      if (!message.isRead &&
          message.receiverId == currentUserId &&
          message.senderId == otherUserId) {
        _messageList[i] = message.copyWith(isRead: true);
      }
    }
  }

  /// 获取两个用户之间的对话列表
  /// [userId1] 第一个用户ID
  /// [userId2] 第二个用户ID
  /// 返回按时间排序的对话消息列表
  List<WhisperEssence> fetchConversation(String userId1, String userId2) {
    return _messageList
        .where(
          (msg) =>
              (msg.senderId == userId1 && msg.receiverId == userId2) ||
              (msg.senderId == userId2 && msg.receiverId == userId1),
        )
        .toList()
      ..sort((a, b) => a.createTime.compareTo(b.createTime));
  }

  /// 获取与某个用户的所有未读消息数量
  /// [currentUserId] 当前用户ID
  /// [otherUserId] 对方用户ID
  /// 返回未读消息数量
  int countUnreadMessages(String currentUserId, String otherUserId) {
    return _messageList
        .where(
          (msg) =>
              !msg.isRead &&
              msg.receiverId == currentUserId &&
              msg.senderId == otherUserId,
        )
        .length;
  }

  /// 获取当前用户的所有未读消息总数
  /// [currentUserId] 当前用户ID
  /// 返回未读消息总数
  int countTotalUnreadMessages(String currentUserId) {
    return _messageList
        .where((msg) => !msg.isRead && msg.receiverId == currentUserId)
        .length;
  }

  /// 清除两个用户之间的所有对话消息
  /// [userId1] 第一个用户ID
  /// [userId2] 第二个用户ID
  /// 返回删除的消息数量
  int purgeConversation(String userId1, String userId2) {
    final initialLength = _messageList.length;

    _messageList.removeWhere(
      (msg) =>
          (msg.senderId == userId1 && msg.receiverId == userId2) ||
          (msg.senderId == userId2 && msg.receiverId == userId1),
    );

    return initialLength - _messageList.length;
  }
}
